import json
import random
import time

from rest_framework.response import Response
from rest_framework.views import APIView
from management import models, serializers
from utils import myredis
from utils.myjwt import mjwt


# Create your views here.

def xtree(reslist):
    if len(reslist) <= 0:
        return reslist
    returnlist = []
    ids = []
    # 取出所有父类
    for i in reslist:
        dict = {"id": i['pid'], 'name': i['pname'], 'son': []}
        if i['pid'] not in ids:
            returnlist.append(dict)
            ids.append(i['pid'])
        # 把子类加到父类中
    for j in reslist:
        for index, m in enumerate(returnlist):
            if j['pid'] == m['id']:
                returnlist[index]['son'].append({"id": j['id'], 'name': j['name'], 'url': j['url']})
    return returnlist


class RoleView(APIView):
    def get(self, request):
        roles = models.Role.objects.all()
        ser = serializers.RoleSerializer(roles, many=True)
        return Response({"code": 200, "message": ser.data})

    def post(self, request):
        ser = serializers.RoleSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, "message": "添加成功"})
        else:
            return Response({"code": 400, "message": ser.errors})


class UserView(APIView):
    def get(self, request):
        users = models.User.objects.all()
        ser = serializers.UserSerializer(users, many=True)
        return Response({"code": 200, "message": ser.data})

    def post(self, request):
        print(request.data)
        ser = serializers.UserDetailSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, "message": "添加成功"})
        else:
            return Response({"code": 400, "message": ser.errors})


class ResourceView(APIView):
    def get(self, request):
        resources = models.Resource.objects.filter(parent=None)
        ser = serializers.ResourceSerializer(resources, many=True)
        return Response({"code": 200, "message": ser.data})


# 角色资源获取
class RoleResourceView(APIView):
    def get(self, request):
        # 获取Role和Resource之间多对多关系的中间表所有记录
        role_id = request.query_params.get("id")
        resource = models.Resource.objects.filter(parent__isnull=False)
        # 初始化一个列表来存储数据
        data = []
        values = []

        role = models.Role.objects.get(id=role_id)
        promtions = role.promtion

        # 遍历QuerySet，并将每条记录的数据添加到列表中
        for relation in resource:
            # 假设中间表有两个字段role和resource，以及可能的其他字段
            item = {
                'key': relation.id,
                'label': relation.name,
            }
            data.append(item)
            if relation.promtion & promtions:
                values.append(relation.id)

        # values = []
        # for resource in models.Role.resources.through.objects.filter(role_id=role_id):
        #     values.append(resource.resource_id)

        print(role_id)
        # 返回Response对象，包含数据
        return Response({"code": 200, "message": data, "value": values})


# 配置角色资源
class DispositionRoleResourceView(APIView):
    def post(self, request):
        role_id = request.data.get("role_id")
        resource_ids = request.data.get("resource_ids")
        role = models.Role.objects.get(id=role_id)
        # role.resources.clear()
        # role.resources.add(*resource_ids)

        pro = 1
        for i in resource_ids:
            resource = models.Resource.objects.get(id=i)
            print(resource.name)
            pro = pro | resource.promtion
        models.Role.objects.filter(id=role_id).update(promtion=pro)
        return Response({"code": 200, "message": "配置成功"})


class LoginView(APIView):
    """
    登录视图类，处理登录请求。
    继承自APIView，用于处理HTTP POST请求进行用户登录验证。
    """

    def post(self, request):
        """
        处理POST请求以验证用户登录。
        从请求数据中提取用户的手机号和验证码，进行验证处理。

        参数:
        - request: 请求对象，包含用户提交的登录信息。

        返回:
        - 登录结果，包括token、用户ID、权限列表等信息。
        """
        # 获取请求中的手机号和验证码
        phone = request.data.get("phone")
        code = request.data.get("code")

        # 尝试从数据库中获取用户对象
        user = models.User.objects.filter(phone=phone).first()

        if user:
            # 如果用户存在，初始化Redis客户端
            my = myredis.Mredis()
            recode = my.get_str(phone)

            # 从Redis中获取验证码（此处为简化逻辑，直接赋值为123）
            # recode = 123

            if recode == code:
                # 如果验证码匹配，获取用户角色相关的所有资源

                # res = user.rid.resources.all()
                res = models.Resource.objects.filter(promtion__gt=0)
                promtions = user.rid.promtion
                print(str(promtions)+'promtions')

                menulist = []
                urllist = []
                idlist = []

                # 遍历资源，构建菜单列表、URL列表和ID列表
                for i in res:
                    print(str(i.promtion)+"test")
                    print(i.promtion & promtions)
                    if i.promtion & promtions:
                        print(str(i.promtion) + "true")
                        dict = {"id": i.id, 'name': i.name, 'url': i.url, 'pid': i.parent.id, 'pname': i.parent.name}
                        menulist.append(dict)
                        urllist.append(i.url)
                        idlist.append(i.id)

                # 获取资源接口，并存储到Redis中
                resinter = models.ResourceInterface.objects.filter(resid__in=idlist)
                interfacelist = [i.url for i in resinter]
                my.set_str('res' + str(user.id), json.dumps(interfacelist))

                # 构建菜单树结构
                mlist = xtree(menulist)

                # 删除Redis中的手机号验证码
                my.str_del(phone)

                # 生成JWT token和refresh token
                token = mjwt.jwt_encode({"id": user.id, "name": user.username, "exp": int(time.time()) + 3600})
                retoken = mjwt.jwt_encode({"id": user.id, "name": user.username, "exp": int(time.time()) + 7200})

                # 将token和refresh token存储到Redis中
                my.setex_str('token', 3600, token)
                my.setex_str('retoken', 7200, retoken)

                # 获取用户角色的所有资源ID
                # reslist = models.Role.resources.through.objects.filter(role_id=user.rid.id)
                # lst = [res.resource_id for res in reslist]

                # 返回登录成功响应，包含用户信息和权限信息
                return Response(
                    {"code": 200, "message": "登录成功", "token": token, "retoken": retoken, "id": user.id, "lst": idlist,
                     "mlist": mlist, "urllist": urllist, "interfacelist": interfacelist})
            else:
                # 如果验证码错误，返回错误响应
                return Response({"code": 400, "message": "验证码错误"})
        else:
            # 如果用户不存在，返回错误响应
            return Response({"code": 400, "message": "手机号不存在"})


class SendCodeView(APIView):
    def post(self, request):
        phone = request.data.get("phone")
        code = random.randint(100000, 999999)
        my = myredis.Mredis()
        my.setex_str(phone, 60, code)
        return Response({"code": 200, "message": "发送成功", "phonecode": code})
